<template>
  <div class="app-container org">
    <el-card>
      <el-row>
        <el-col :span="24">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>
      <el-form ref="queryRef" label-width="100" :model="queryParams">
        <el-row>
          <el-col :span="5">
            <el-form-item label="标准物质名称：" prop="bzwzName" label-width="">
              <el-input clearable maxlength="100" placeholder="请输入" v-model="queryParams.bzwzName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="种类：" prop="bzwzType" label-width="80">
              <el-select placeholder="请选择" clearable v-model="queryParams.bzwzType" @keyup.enter="handleQuery" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_bzwz_type)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="唯一性编号：" prop="bzwzCode" label-width="">
              <el-input clearable maxlength="100" placeholder="请输入唯一性编号" v-model="queryParams.bzwzCode"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="批次号：" prop="produceCode" label-width="80">
              <el-input clearable maxlength="100" placeholder="请输入批次号" v-model="queryParams.produceCode"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="检测项目：" prop="bucketId" label-width="80">
              <el-select v-model="queryParams.bucketId" clearable filterable remote reserve-keyword remote-show-suffix
                :remote-method="remoteMethod" :loading="loading" style="width: 100%">
                <el-option v-for="item in jcxmList" :key="item.bucketId" :value="item.bucketId" :label="item.jcxmName">
                  <span v-html="transformation(item.jcxmName)"></span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="检测项目类型：" prop="isSingle" label-width="">
              <el-select placeholder="请选择" clearable v-model="queryParams.isSingle" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_bzwz_jcxm_type)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="归属类别：" prop="gsType" label-width="80">
              <el-select placeholder="请选择" clearable v-model="queryParams.gsType" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_bzwz_gslb)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="入库日期：" prop="expirationType">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" :clearable="false"
                :editable="false" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="生产厂商：" prop="produceName" label-width="80">
              <el-input clearable maxlength="100" placeholder="请输入生产厂商" v-model="queryParams.produceName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="定值单位：" prop="dzUnit" label-width="80">
              <el-input clearable maxlength="100" placeholder="请输入定值单位" v-model="queryParams.dzUnit"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="保存位置：" prop="saveLocation" label-width="80">
              <el-input clearable maxlength="100" placeholder="请输入保存位置" @keyup.enter="handleQuery"
                v-model="queryParams.saveLocation" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-row justify="center">
              <el-radio label="0" v-model="queryParams.isLike">模糊搜索</el-radio>
              <el-radio label="1" v-model="queryParams.isLike">精准搜索</el-radio>
            </el-row>
          </el-col>
          <el-col :span="3">
            <el-button type="success" @click="handleQuery">搜索</el-button>
            <el-button class="resetBtn" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">标准物质入库列表</p>
        <p class="totalStyle">共 {{ total }} 条数据</p>
        <el-button type="success" link icon="Plus" @click="singleAdd"
          style="padding-bottom: 10px; margin-left: 10px">单个入库</el-button>
        <el-row style="padding-bottom: 5px">
          <el-button type="success" style="margin-left: 30px" link icon="Plus" @click="importTemplate">导出数据</el-button>
          <el-button type="success" style="margin-left: 10px" link icon="Plus">批量入库</el-button>
          <el-button type="success" style="margin-left: 10px" link icon="Plus" @click="handleExport">导出入库记录</el-button>
          <el-button type="success" style="margin-left: 10px" link icon="Plus" @click="handleImport">导入入库记录</el-button>
        </el-row>
        <el-table ref="mainTableRef" :data="bzwzTable" @selection-change="handleSelChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="唯一性编号" prop="bzwzCode" align="center" />
          <el-table-column label="标准物质名称" prop="bzwzName" align="center" width="230" />
          <el-table-column label="种类" prop="bzwzType" align="center">
            <template #default="scope">
              <dict-tag :options="sys_bzwz_type" :value="scope.row.bzwzType" />
            </template>
          </el-table-column>
          <el-table-column label="生产厂商" prop="produceName" align="center" />
          <el-table-column label="批次号" prop="produceCode" align="center" />
          <el-table-column label="入库日期" prop="createDate" align="center" />
          <el-table-column label="有效日期" prop="yxDate" align="center" />
          <el-table-column label="保存位置" prop="saveLocation" align="center" />
          <el-table-column label="保存方式" prop="saveCondition" align="center" />
          <el-table-column label="规格" prop="totalGg" align="center">
            <template #default="scope">
              {{ scope.row.totalGg }}
              <span v-html="transformation(scope.row.ggUnitName)"></span>
            </template>
          </el-table-column>
          <el-table-column label="单价(元)" prop="price" align="center"/>
          <el-table-column label="检测项目数" prop="jcxmCount" align="center">
            <template #default="scope">
              <el-button link @click="jcxmCountClick(scope.row.bzwzId)">{{
                scope.row.jcxmName ? scope.row.jcxmName : scope.row.jcxmCount
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="xqBzwz(scope.row.bzwzId, 1)">引用</el-button>
              <el-button link type="success" @click="xqBzwz(scope.row.bzwzId, 3)">编辑</el-button>
              <el-button link type="success" @click="delBzwz(scope.row.bzwzId)" v-if="!scope.row.useGg">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-row>
    </el-card>
    <el-dialog :class="'el-dialog-theme3'" :title="upload.title" v-model="upload.open" width="400px"
      append-to-body draggable :close-on-click-modal="false">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleUploadError"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="success" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitFileForm">确 定</el-button>
          <el-button type="danger" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 点击行内检测项目数的弹窗 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="jcxmOpen" @close="closedDialog" :title="title">
      <el-row>
        <p class="pinformation">检测项目列表</p>
        <p class="totalStyle">共 {{ multiplexTable.length }} 条数据</p>
      </el-row>
      <el-table :data="multiplexTable">
        <el-table-column label="检测项目" prop="jcxmName" align="center">
          <template #default="scope">
            <span v-html="transformation(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="浓度值" prop="con" align="center" />
        <el-table-column label="浓度值单位" prop="conUnit" align="center">
          <template #default="scope">
            <span v-html="transformation(scope.row.conUnitName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="不确定度值" prop="notvalue" align="center" />
        <el-table-column label="不确定度单位" prop="notvalueUnit" align="center">
          <template #default="scope">
            <span v-html="transformation(scope.row.subNotvalueName)"></span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="jcxmOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 单个入库和引用弹窗 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      @close="closedInDialog" v-model="rkOrYyOpen" :title="rkOrYyTitle" width="1100">
      <el-form label-width="110" ref="rkOrYyRef" :model="form" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="标准物质名称：" prop="bzwzName">
              <el-input clearable maxlength="100" v-model="form.bzwzName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="唯一性编号：">
              <onlinePreview :typeId="serialTypeId" @emitForm="emitForm" ref="onlinePreviewRef"
                v-if="!form.bzwzCode && (form.gsType === 0 || form.gsType)"></onlinePreview>
              <span v-if="form.bzwzCode">{{ form.bzwzCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="种类：" prop="bzwzType">
              <el-select placeholder="请选择" clearable v-model="form.bzwzType" filterable style="width: 100%;">
                <el-option v-for="dict in sys_bzwz_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="出厂编号：" prop="factoryCode">
              <el-input clearable maxlength="100" v-model="form.factoryCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产批号：" prop="produceCode">
              <el-input clearable maxlength="100" v-model="form.produceCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="定值单位：" prop="dzUnit">
              <el-input clearable maxlength="100" placeholder="请输入定值单位" v-model="form.dzUnit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库日期：" prop="createDate">
              <el-date-picker v-model="form.createDate" placeholder="请选择要求完成时间" type="date" style="width: 100%;"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效期：" prop="yxDate">
              <el-date-picker v-model="form.yxDate" placeholder="请选择有效期" style="width: 100%;" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="溶剂：" prop="rj">
              <el-input clearable maxlength="100" v-model="form.rj"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-row :gutter="5">
              <el-col :span="15">
                <el-form-item label="规格：" prop="totalGg">
                  <el-input-number clearable :min="1" v-model="form.totalGg" controls-position="right" style="width: 100%"
                    :disabled="(form.useGg ? true : false) && form.useGg !== 0"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item prop="ggUnit" label-width="0">
                  <el-select v-model="form.ggUnit" placeholder="" clearable filterable style="width: 100%;">
                    <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                      <span v-html="transformation(item.unitName)"></span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保存方式：" prop="saveCondition">
              <el-input clearable maxlength="100" v-model="form.saveCondition"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归属类别：" prop="gsType">
              <el-select placeholder="请选择" clearable v-model="form.gsType" @change="gsTypeChange" style="width: 100%;"
                filterable>
                <el-option v-for="dict in sys_bzwz_gslb" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单价（元）：" prop="price">
              <el-input clearable v-model="form.price" controls-position="right"
                oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                @blur="form.price = $event.target.value"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产厂商：" prop="produceName">
              <el-input clearable maxlength="100" v-model="form.produceName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="代理厂商：" prop="agentName">
              <el-input clearable maxlength="100" v-model="form.agentName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库人：" prop="bzwzAdminId">
              <el-select v-model="form.bzwzAdminId" filterable clearable style="width: 100%;">
                <el-option v-for="item in userList" :value="item.userId" :key="item.userId"
                  :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证书位置：" prop="certificateLocation">
              <el-input clearable maxlength="100" v-model="form.certificateLocation"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保存位置：" prop="saveLocation">
              <el-input clearable maxlength="100" v-model="form.saveLocation"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-row :gutter="5">
              <el-col :span="17">
                <el-form-item label="开封后有效期：" prop="yxPeriod">
                  <el-input-number clearable :min="1" v-model="form.yxPeriod" controls-position="right"
                    style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item prop="yxUnit" label-width="0">
                  <el-select v-model="form.yxUnit" placeholder="" clearable filterable style="width: 100%;">
                    <el-option v-for="item in yxUnitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                      <span v-html="transformation(item.unitName)"></span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <p class="pinformation">证书附件</p>
        <fileUpload v-model="form.fileList"></fileUpload>
        <el-row>
          <p class="pinformation">检测项目列表</p>
          <p class="totalStyle">共 {{ form.bzwzJcxmList.length }} 条数据</p>
          <el-row style="padding-bottom: 5px">
            <el-button link icon="Plus" @click="handleJcxmList" style="margin-left: 10px">新增</el-button>
            <el-button link @click="delJcxmList" :disabled="!ids.length" style="margin-left: 10px">批量删除</el-button>
          </el-row>
        </el-row>
        <el-table :data="form.bzwzJcxmList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="检测项目" prop="bucketId" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.bucketId" clearable filterable remote reserve-keyword remote-show-suffix
                :remote-method="remoteMethod1" @click="getIndex(scope.$index)" :loading="loading1" style="width: 100%">
                <el-option v-for="item in scope.row.jcxmList" :key="item.bucketId" :value="item.bucketId"
                  :label="item.jcxmName">
                  <span v-html="transformation(item.jcxmName)"></span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="浓度值" prop="con" align="center">
            <template #default="scope">
              <el-input-number controls-position="right" style="width: 100%" :min="0" clearable maxlength="100"
                v-model="scope.row.con" />
            </template>
          </el-table-column>
          <el-table-column label="浓度值单位" prop="conUnit" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.conUnit" placeholder="" clearable filterable>
                <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                  <span v-html="transformation(item.unitName)"></span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="不确定度值" prop="notvalue" align="center">
            <template #default="scope">
                <el-input clearable maxlength="100" v-model="scope.row.notvalue"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="不确定度单位" prop="notvalueUnit" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.notvalueUnit" placeholder="" clearable filterable>
                <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                  <span v-html="transformation(item.unitName)"></span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="delJcxm(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="saveBzwz">保 存</el-button>
          <el-button type="danger" @click="rkOrYyOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BzwzOutin">
import onlinePreview from "@/components/onlinePreview/index.vue";
import {
  listLedger,
  bzwzList,
  delbzwzList,
  BzwzViewForm,
  addBzwz,
  getJcxmList,
} from "@/api/resource/ledger";
import { getCurrentTime, getCurrentUser } from "@/api/common";
import { getSeqId } from "@/api/common";
import { getUnitList } from "@/api/store/unit";
import { listUser } from "@/api/contract/check";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();
const { sys_bzwz_type, sys_bzwz_gslb, sys_bzwz_gqlx, sys_bzwz_jcxm_type } =
  proxy.useDict(
    "sys_bzwz_type",
    "sys_bzwz_gslb",
    "sys_bzwz_gqlx",
    "sys_bzwz_jcxm_type"
  );

const bzwzTable = ref([]);
const multiplexTable = ref([]);
const jcxmList = ref([]);
const jcxmOpen = ref(false);
const rkOrYyOpen = ref(false);
const rkOrYyTitle = ref("");
const useOpen = ref(false);
const title = ref("查看检测项目");
const serialTypeId = ref(37);
const onlinePreviewRef = ref(null);
function emitForm(val) {
  form.value.params["serialData"] = val;
}
const data = reactive({
  form: { bzwzJcxmList: [], fileList: [], params: {} },
  queryParams: {
    pageNum: 1, // 当前页数
    pageSize: 10, // 当前页数据条数
    isLike: "0",
    bzwzType: -1,
    isSingle: -1,
    gsType: -1,
  },
  rules: {
    bzwzCode: [
      { required: true, message: "唯一性编号不能为空", trigger: "blur" },
    ],
    bzwzName: [
      { required: true, message: "标准物质名称不能为空", trigger: "blur" },
    ],
    yxDate: [
      { required: true, message: "有效期不能为空", trigger: "blur" },
    ],
    bzwzType: [{ required: true, message: "种类不能为空", trigger: "blur" }],
    totalGg: [{ required: true, message: "规格数量不能为空", trigger: "blur" }],
    // price: [{ required: true, message: "单价不能为空", trigger: "blur" }],
    ggUnit: [{ required: true, message: "规格单位不能为空", trigger: "blur" }],
    gsType: [{ required: true, message: "归属类别不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const total = ref(0);
const dateRange = ref([]);
function getList() {
  listLedger(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      bzwzTable.value = res.rows;
      total.value = res.total;
    }
  );
}
getList();

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.isLike = "0";
  handleQuery();
}

function jcxmCountClick(row) {
  bzwzList({ bzwzId: row }).then((res) => {
    multiplexTable.value = res.data;
    jcxmOpen.value = true;
  });
}

function closedDialog() {
  multiplexTable.value = [];
}

function delBzwz(bzwzId) {
  proxy.$modal
    .confirm("是否确认删除该条记录？")
    .then(function () {
      delbzwzList(bzwzId).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        getList();
      });
    })
    .catch(() => { });
}

function xqBzwz(bzwzId, isOpen) {
  BzwzViewForm(bzwzId).then((res) => {
    form.value = res.data;
    form.value.bzwzJcxmList.forEach(item => {
      item.jcxmList = [{ bucketId: item.bucketId, jcxmName: item.jcxmName }]
    })
    form.value.params = {};
    if (isOpen == 1) {
      rkOrYyOpen.value = true;
      rkOrYyTitle.value = "引用标准物质";
      form.value.isDel = true;
      delete form.value.useGg;
      delete form.value.bzwzCode;
      form.value.bzwzJcxmList.forEach((item, index) => {
        getSeqId().then((res) => {
          form.value.bzwzJcxmList[index].bJId = res.data;
        });
      });
    } else if (isOpen == 3) {
      rkOrYyOpen.value = true;
      rkOrYyTitle.value = "编辑标准物质";
    }
  });
}

function closedInDialog() {
  form.value = {
    bzwzJcxmList: [],
    fileList: [],
    params: {},
  };
  proxy.$refs["rkOrYyRef"]?.clearValidate();
}

function singleAdd() {
  getCurrentTime().then((res) => {
    form.value.createDate = res.data;
  });
  getCurrentUser().then((res) => {
    form.value.bzwzAdminId = res.data;
  });
  rkOrYyOpen.value = true;
  rkOrYyTitle.value = "标准物质入库";
  form.value.params = {};
}

function saveBzwz() {
  proxy.$refs["rkOrYyRef"].validate((valid) => {
    if (valid) {
      if (!form.value.bzwzId && !form.value.params["serialData"]) {
        proxy.$modal.msgError("标准物质唯一编号不能为空");
        return false;
      }
      if (form.value.bzwzJcxmList.length) {
        if (form.value.isDel) {
          delete form.value.bzwzId;
        }
        addBzwz(form.value).then((res) => {
          rkOrYyOpen.value = false;
          proxy.$modal.msgSuccess(res.msg);
          getList();
        });
      } else {
        proxy.$modal.msgError("检测项目列表不能为空");
      }
    }
  });
}

function handleJcxmList() {
  getSeqId().then((res) => {
    form.value.bzwzJcxmList.push({ bJId: res.data });
  });
}

const tempJcxmList = ref([]);
const ids = ref([]);
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => {
    return item.bJId;
  });
  tempJcxmList.value = form.value.bzwzJcxmList.filter((row) => {
    return selection.indexOf(row) == -1;
  });
}

function delJcxmList() {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      form.value.bzwzJcxmList = tempJcxmList.value;
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function delJcxm(row) {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      form.value.bzwzJcxmList.splice(row, 1);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

const unitList = ref([]);
const yxUnitList = ref([]);
getUnitList().then((res) => {
  unitList.value = res.data;
  yxUnitList.value = res.data;
});

function handleSelChange(selection) {
  multiplexTable.value = selection;
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

function transformation(row) {
  const a = proxy.getSupAndSub(row);
  return a;
}

const userList = ref([]);
listUser().then((res) => {
  userList.value = res.data;
});

function gsTypeChange(row) {
  row == 1 ? (serialTypeId.value = 38) : (serialTypeId.value = 37);
}

// -------------------导入模板逻辑-------------------
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/resource/bzwz/importData",
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "标准物质入库登记导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "/resource/bzwz/export",
    {
      ...queryParams.value,
    },
    `标准物质入库登记表_${new Date().getTime()}.xlsx`
  );
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("/resource/bzwz/importTemplate", {
  }, `标准物质模板_${new Date().getTime()}.xlsx`);
};

const loading = ref(false);
const loading1 = ref(false);

function remoteMethod(val) {
  if (val) {
    loading.value = true;
    setTimeout(() => {
      getJcxmList({ jcxmName: val }).then((res) => {
        loading.value = false;
        jcxmList.value = res.rows;
      });
    }, 200);
  } else {
    jcxmList.value = [];
  }
}

const listIndex = ref(0);
function getIndex(index) {
  listIndex.value = index;
}

function remoteMethod1(val) {
  if (val) {
    loading1.value = true;
    setTimeout(() => {
      getJcxmList({ jcxmName: val }).then((res) => {
        loading1.value = false;
        form.value.bzwzJcxmList[listIndex.value].jcxmList = res.rows;
      });
    }, 200);
  } else {
    form.value.bzwzJcxmList[listIndex.value].jcxmList = [];
  }
}

// 上传失败
function handleUploadError(err) {
  upload.isUploading = false;
  proxy.$modal.msgError("导入数据失败，原因：" + err.message);
}
</script>

<style lang="scss" scoped>
.el-radio {
  margin-right: 5px;
}
</style>
